# -*- coding:utf-8-*-
# 14.3.1 修改User-Agent
# 两种途径：实例化Request 对象的时候将headers参数传进去
# 通过add_header()方法往Request对象添加headers

# headers必须是一个字典的形式
# import urllib.request
# import urllib.parse
# import json
#
# content = input("请输入需要翻译的内容：")
# url = "http://fanyi.youdao.com/translate?smartresult = dict&smartresult=rule&smartresult=" \
#       "ugc&sessionFrom = http://www.youdao.com/"
# head = {}
# head['Referer'] = 'http://fanyi.youdao.com'
# head['User-Agent'] = 'Mozilia/5.0(Macintosh;Intel Mac OS X 10_10_1) AppleWebKit/537.36(KHTML,like Gecko)' \
#                      'Chrome/39.0.2171.95 Safari/537.36X-Requested-With:XMLHttpRequest'
# data = {}
# data['type'] = 'AUTO'
# data['i'] = 'I love FishC.com!'
# data['doctype'] = 'json'
# data['xmlVersion'] = '1.6'
# data['keyfrom'] = 'fanyi.web'
# data['ue'] = 'UTF-8'
# data['typeResult'] = 'true'
# data = urllib.parse.urlencode(data).encode('utf-8')
#
# req = urllib.request.Request(url, data, head)
# response = urllib.request.urlopen(req)
# html = response.read().decode('utf-8')
# # 编码问题：http://bbs.fishc.com/thread-56452-1-1.html
# target = json.loads(html)  # 解析JSON格式字符串
# # type(target)
# print("翻译结果是：%s" % (target['translateResult'][0][0]['tgt']))


# 在Requset对象生成之后，用add_header()方法追加进去：
import urllib.request
import urllib.parse
import json

content = input("请输入需要翻译的内容：")
url = "http://fanyi.youdao.com/translate?smartresult = dict&smartresult=rule&smartresult=" \
      "ugc&sessionFrom = http://www.youdao.com/"
data = {}
data['type'] = 'AUTO'
data['i'] = 'I love FishC.com!'
data['doctype'] = 'json'
data['xmlVersion'] = '1.6'
data['keyfrom'] = 'fanyi.web'
data['ue'] = 'UTF-8'
data['typeResult'] = 'true'
data = urllib.parse.urlencode(data).encode('utf-8')
req = urllib.request.Request(url, data)
req.add_header('Referer', 'http://fanyi.youdao.com')
req.add_header('User-Agent', 'Mozilia/5.0(Macintosh;Intel Mac OS X 10_10_1) AppleWebKit/537.36(KHTML,like Gecko)' \
                             'Chrome/39.0.2171.95 Safari/537.36X-Requested-With:XMLHttpRequest')
response = urllib.request.urlopen(req)
html = response.read().decode('utf-8')
# 编码问题：http://bbs.fishc.com/thread-56452-1-1.html
target = json.loads(html)  # 解析JSON格式字符串
# type(target)
print("翻译结果是：%s" % (target['translateResult'][0][0]['tgt']))
